//app.js
App({
  onLaunch: function () {

    var dakaToken= wx.getStorageSync('daka_token')
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        var code = res.code
        this.globalData.code = code
      }
    })

    var app = this;
    wx.getSetting({
      success(res) {
        console.log(res);
        if (res.authSetting['scope.userInfo']){
              wx.getUserInfo({
                success: res => {
                  console.log(res);
                  app.globalData.userInfo = res.userInfo
                  if(!dakaToken){
                    var rawData = res.rawData;
                    var signature = res.signature;
                    var encryptedData = res.encryptedData;
                    var iv = res.iv;
                    wx.request({
                      url: 'https://daka.rzkeji.com/api/auth/wxLogin',
                      data: {
                        "code": app.globalData.code,
                        "raw_data": rawData,
                        "signature": signature,
                        'iv': iv,
                        'encryptedData': encryptedData
                      },
                      method: "POST",
                      header: {
                        'content-type': 'application/json'
                      },
                      success: function (res) {
                        if (res.data.level == "success") {
                          wx.setStorageSync('daka_token', res.data.data);

                        } else {
                          wx.showToast({
                            title: res.data.message,
                            icon: 'none',
                            duration: 2000
                          })
                        }
                      }
                    });
                  }
                },
            fail:function(){
              wx.navigateTo({
                url: '../login/login'
              })
            }
          })
        }else{
          wx.navigateTo({
            url: '../login/login'
          })
        }
      }
    })
  },
  globalData: {
    userInfo:"",
    code:""
  }
})